package com.hhd.pdf.variable;

import com.alibaba.fastjson.JSONObject;
import lombok.Builder;

import java.util.List;

@Builder
public class SimpleVariableParser {
    JSONObject renderData;
    String formula;

    public String parse() {
        try {
            CompositeFormula compositeFormula = CompositeFormula.formula(formula);
            List<ParsedFormula> formulas = compositeFormula.getFormulas();
            for (ParsedFormula parsedFormula : formulas) {
                String[] path = parsedFormula.getPath();
                JSONObject temp = renderData;
                for (int i = 0; i < path.length - 1; i++) {
                    temp = temp.getJSONObject(path[i]);
                }
                parsedFormula.setFormulaValue(getFormulaValue(parsedFormula, temp));
            }
            return compositeFormula.joinFormulas();
        } catch (Exception e) {
        }
        return "";
    }

    private static String getFormulaValue(ParsedFormula parsedFormula, JSONObject temp) {
        ParsedFormula tempFormula = ParsedFormula.formula("");
        tempFormula.setFormulaValue(temp.get(parsedFormula.getLastPath()));
        return tempFormula.getFormulaValue();
    }
}
